package com.sidianzhong.sdz.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.sidianzhong.sdz.annotation.UserLoginToken;
import com.sidianzhong.sdz.model.CoinInfo;
import com.sidianzhong.sdz.model.User;
import com.sidianzhong.sdz.model.UserWallet;
import com.sidianzhong.sdz.model.commond.PhoneCode;
import com.sidianzhong.sdz.model.commond.UserToken;
import com.sidianzhong.sdz.service.CoinInfoService;
import com.sidianzhong.sdz.service.ConstantService;
import com.sidianzhong.sdz.service.UserService;
import com.sidianzhong.sdz.service.UserWalletService;
import com.sidianzhong.sdz.service.commond.RedisService;
import com.sidianzhong.sdz.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

@Api(description = "登录注册相关")
@Controller
public class LoginController {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    RedisService redisService;

    @Autowired
    UserService userService;

    @Autowired
    UserWalletService userWalletService;
    @Autowired
    ConstantService constantService;

    @Autowired
    CoinInfoService coinInfoService;

    @ApiOperation(value = "安卓检测版本")
    @RequestMapping(value = "/checkUpdate", method = RequestMethod.GET)
    public ResponseEntity<ResultModel> checkUpdate() throws IOException {
        String path = Constants.FILE_PATH + "/version.json";
        //String path ="F:/001/version.json";
        return FileDownload.checkUpdate(path);
    }

    /**
     * 检查苹果版本更新
     *
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "ios检测版本")
    @RequestMapping(value = "/checkIOSUpdate", method = RequestMethod.GET)
    public ResponseEntity<ResultModel> checkIOSUpdate() throws IOException {
        String path = Constants.IOS_FILE_PATH + "/version_ios.json";
        //String path ="F:/001/version_ios.json";
        return FileDownload.checkUpdate(path);
    }

    /**
     * 文件下载
     */
    @ApiOperation(value = "下载接口")
    @GetMapping(value = "/filedownload")
    public void filedownload(HttpServletRequest request, HttpServletResponse response) {
        FileTemplateUtils.downloanFromExcelTemplate("update.json", "file", request, response);
    }


    @ApiOperation(value = "登录")
    @RequestMapping(value = "/login",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object login(
            HttpServletRequest request,
            @RequestParam(value = "phone") String phone,
            @RequestParam(value = "password") String password,
            @RequestParam(value = "area", required = false, defaultValue = "86") String area
    ) {
        Integer user_id = (Integer) request.getAttribute("USER_ID");

        ResourceBundle myResourcesBundle = International.getLanguage(request);
        if (phone == null || phone.isEmpty() || !phone.matches(Matches.PHONE_MATCHES))
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNameOrPassWordError"), HttpStatus.OK);
        if (password == null || password.isEmpty() || !password.matches(Matches.PASSWORD_MATCHES))
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNameOrPassWordError"), HttpStatus.OK);

        User user = userService.getUserByPhone(phone);
        if (user == null) {
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNotFound"), HttpStatus.OK);
        }
        user.setLoginNum(user.getLoginNum()+1);
        userService.update(user);

        //验证密码是否正确
        if (!user.getLoginPassword().equals(password)) {
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNameOrPassWordError"), HttpStatus.OK);
        }

        UserToken userToken = redisService.createToken(user);
        return new ResponseEntity<>(ResultModel.ok(userToken), HttpStatus.OK);
    }

    @ApiOperation(value = "发送手机短信")
    @RequestMapping(value = "/sendPhoneMassage",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object sendPhoneMassage(
            @RequestParam(value = "phone") String phone,
            @RequestParam(value = "area", required = false, defaultValue = "86") String area
    ) throws IOException {
        if (true) {
            JSONObject jsonObjectRet = new JSONObject();
            jsonObjectRet.put("result", "成功");
            return new ResponseEntity<>(ResultModel.ok(jsonObjectRet), HttpStatus.OK);
        }
        long nowDate = new Date().getTime();
        String str = String.valueOf(nowDate);
        String code = str.substring(7);

        System.out.println(code);
        PhoneCode code1 = redisService.getCode(phone);
        if (null != code1.getCode()) {
            long nowTime = System.currentTimeMillis();
            long lastTime = code1.getCurrentTime();
            if (((nowTime - lastTime)) < 30 * 1000) {
                ResourceBundle myResourcesBundle = International.getLanguage(request);
                return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "smsCodeFail"), HttpStatus.OK);
            }
        }
        int i = SendPhoneMessage.sendMsg(phone, code);
        PhoneCode phoneCode = redisService.createCode(phone, code);
        JSONObject jsonObjectRet = new JSONObject();
        if (i == 200) {
            jsonObjectRet.put("result", "成功");
            return new ResponseEntity<>(ResultModel.ok(jsonObjectRet), HttpStatus.OK);
        } else {
            ResourceBundle myResourcesBundle = International.getLanguage(request);
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "smsCodeFail"), HttpStatus.OK);
        }
    }


    @UserLoginToken
    @ApiOperation(value = "发送修改密码手机短信")
    @RequestMapping(value = "/sendUpdatePhoneMassage",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object sendUpdatePhoneMassage(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token
    ) throws IOException {
        Integer user_id = (Integer) request.getAttribute("USER_ID");
        User user = userService.get(user_id);

        ResourceBundle myResourcesBundle = International.getLanguage(request);
        if (user == null) {
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNotFound"), HttpStatus.OK);
        }
        String area = user.getArea();
        String phone = user.getPhone();

        long nowDate = new Date().getTime();
        String str = String.valueOf(nowDate);
        String code = str.substring(7);

        System.out.println(code);
        PhoneCode code1 = redisService.getCode(phone);
        if (null != code1.getCode()) {
            long nowTime = System.currentTimeMillis();
            long lastTime = code1.getCurrentTime();
            if (((nowTime - lastTime)) < 30 * 1000) {
                return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "smsCodeFail"), HttpStatus.OK);
            }
        }
        int i = SendPhoneMessage.sendMsg(phone, code);
        PhoneCode phoneCode = redisService.createCode(phone, code);
        JSONObject jsonObjectRet = new JSONObject();
        if (i == 200) {
            jsonObjectRet.put("result", "成功");
            return new ResponseEntity<>(ResultModel.ok(jsonObjectRet), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "smsCodeFail"), HttpStatus.OK);
        }
    }

    @ApiOperation(value = "注册")
    @RequestMapping(value = "/register",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object register(
            HttpServletRequest request,
            @RequestParam(value = "phone") String phone,
            @RequestParam(value = "password") String password,
            @RequestParam(value = "invCode", required = false) String invCode,
            @RequestParam(value = "code", required = false) String code,
            @RequestParam(value = "area", required = false, defaultValue = "86") String area
    ) throws IOException {

        ResourceBundle myResourcesBundle = International.getLanguage(request);
        String s = constantService.selectValueByKey(Constants.NODE_SWITCH);
        if ("true".equals(s)) {
            if (invCode == null) {
                return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "invCodeError"), HttpStatus.OK);
            }
        }

        if (phone == null || phone.isEmpty() || !phone.matches(Matches.PHONE_MATCHES))
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNameOrPassWordError"), HttpStatus.OK);
        if (password == null || password.isEmpty() || !password.matches(Matches.PASSWORD_MATCHES))
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNameOrPassWordError"), HttpStatus.OK);
//        if (code == null || code.isEmpty() || !code.matches(Matches.PHONE_CODE_MATCHES) || !code.equals(redisService.getCode(phone).getCode())) {
//            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "smsCodeError"), HttpStatus.OK);
//        }

        User user = userService.getUserByPhone(phone);
        if (user != null) {
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userHasExists"), HttpStatus.OK);
        }

        Date date = new Date();
        //开始注册
        User newUser = new User();
        newUser.setUserName(phone);
        newUser.setPhone(phone);
        newUser.setArea(area);

        newUser.setLoginPassword(password);
        newUser.setLoginNum(0);
        newUser.setStatus(0);
        newUser.setCreateTime(date);
        newUser.setLastUpdateTime(date);
        if (invCode!=null){
            User userByCode = userService.getUserByCode(invCode);
            if (userByCode!=null){
                newUser.setInviter(userByCode.getId());
            }
        }

        if ((newUser = userService.create(newUser)) == null) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        newUser.setInvitationCode(CodeProcess.encode(newUser.getId()));
        userService.update(newUser);
        //创建地址
        CoinInfo coinInfo = new CoinInfo();
//        coinInfo.setIsdisplay(1);
        List<CoinInfo> list = coinInfoService.getList(1, 1000, "coin_id", "asc", coinInfo);
        User finalNewUser = newUser;

        list.stream().forEach(info -> {
            String address = null;
            String privatekey = null;

            WalletProcess walletProcess = new WalletProcess();
            if (info.getCoinId() == 10000001) {
                WalletAccount walletAccount = walletProcess.createUSDTAccount();
                address = walletAccount.getWalletEthAddress();
                privatekey = walletAccount.getWalletEthPrivatekey();
            }
            UserWallet userWallet = new UserWallet();
            userWallet.setAddress(address);
            userWallet.setPrivatekey(privatekey);
            userWallet.setUserId(finalNewUser.getId());
            userWallet.setAmount(0.0);
            userWallet.setStatus(0);
            userWallet.setCoinId(info.getCoinId());
            userWallet.setCreateTime(date);
            userWallet.setLastUpdateTime(date);
            userWalletService.create(userWallet);
        });

        redisService.deleteCode(code);
        return new ResponseEntity<>(ResultModel.ok(true), HttpStatus.OK);
    }


    @UserLoginToken
    @ApiOperation(value = "退出登录")
    @RequestMapping(value = "/loginOut",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object loginOut(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token
    ) {
        Integer user_id = (Integer) request.getAttribute("USER_ID");
        Boolean aBoolean = redisService.deleteCode(user_id.toString());
        return new ResponseEntity<>(ResultModel.ok(aBoolean), HttpStatus.OK);
    }


    @ApiOperation(value = "忘记密码")
    @RequestMapping(value = "/forgetPassword",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object forgetPassword(
            HttpServletRequest request,
            @RequestParam(value = "phone") String phone,
            @RequestParam(value = "newPassword") String password,
            @RequestParam(value = "code", required = false) String code
    ) {
        ResourceBundle myResourcesBundle = International.getLanguage(request);
        if (phone == null || phone.isEmpty() || !phone.matches(Matches.PHONE_MATCHES))
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNameOrPassWordError"), HttpStatus.OK);
        if (password == null || password.isEmpty() || !password.matches(Matches.PASSWORD_MATCHES))
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNameOrPassWordError"), HttpStatus.OK);
//        if (code == null || code.isEmpty() || !code.matches(Matches.PHONE_CODE_MATCHES) || !code.equals(redisService.getCode(phone).getCode())) {
//            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "smsCodeError"), HttpStatus.OK);
//        }

        User user = userService.getUserByPhone(phone);
        if (user == null) {
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNameOrPassWordError"), HttpStatus.OK);
        }

        //开始修改
        user.setLoginPassword(password);
        user.setStatus(0);
        if (userService.update(user) == 0) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        redisService.deleteCode(phone);
        //修改成功
        return new ResponseEntity<>(ResultModel.ok(true), HttpStatus.OK);

    }

    @UserLoginToken
    @ApiOperation(value = "修改密码")
    @RequestMapping(value = "/updatePassword",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object updatePassword(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "oldPassword") String oldPassword,
            @RequestParam(value = "newPassword") String newPassword,
            @RequestParam(value = "code", required = false) String code
    ) {
        Integer user_id = (Integer) request.getAttribute("USER_ID");
        ResourceBundle myResourcesBundle = International.getLanguage(request);
        User user = userService.get(user_id);
        if (user == null) {
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNotFound"), HttpStatus.OK);
        }

        if (oldPassword == null || oldPassword.isEmpty() || !oldPassword.matches(Matches.PASSWORD_MATCHES))
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNameOrPassWordError"), HttpStatus.OK);
        if (newPassword == null || newPassword.isEmpty() || !newPassword.matches(Matches.PASSWORD_MATCHES))
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "userNameOrPassWordError"), HttpStatus.OK);
//        if (code == null || code.isEmpty() || !code.matches(Matches.PHONE_CODE_MATCHES) || !code.equals(redisService.getCode(user.getPhone()).getCode())) {
//            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "smsCodeError"), HttpStatus.OK);
//        }

        //验证历史密码是否正确
        if (!user.getLoginPassword().equals(oldPassword)) {
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "orderPassWordError"), HttpStatus.OK);
        }
        //开始修改
        user.setLoginPassword(newPassword);
        user.setStatus(0);
        if (userService.update(user) == 0) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        //修改成功
        return new ResponseEntity<>(ResultModel.ok(true), HttpStatus.OK);

    }


    @UserLoginToken
    @ApiOperation(value = "修改支付密码")
    @RequestMapping(value = "/updatePayPassword",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object updatePayPassword(
            @RequestHeader(value = "X-Auth-Token", required = false) String token,
            @RequestParam(value = "payPassword") String payPassword,
            @RequestParam(value = "code") String code
    ) {
        ResourceBundle myResourcesBundle = International.getLanguage(request);
        Integer user_id = (Integer) request.getAttribute("USER_ID");
        User user = userService.get(user_id);
        if (payPassword == null || payPassword.isEmpty() || !payPassword.matches(Matches.JY_PASSWORD_MATCHES)) {
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "payPasswordError"), HttpStatus.OK);
        }

        user.setPayPassword(payPassword);
        userService.update(user);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", true);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "设置支付密码")
    @RequestMapping(value = "/setPayPassword",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object setPayPassword(
            @RequestHeader(value = "X-Auth-Token", required = false) String token,
            @RequestParam(value = "payPassword") String payPassword

    ) {
        ResourceBundle myResourcesBundle = International.getLanguage(request);
        Integer user_id = (Integer) request.getAttribute("USER_ID");
        if (payPassword == null || payPassword.isEmpty() || !payPassword.matches(Matches.JY_PASSWORD_MATCHES)) {
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "payPasswordError"), HttpStatus.OK);
        }
        User user = userService.get(user_id);
        user.setPayPassword(payPassword);
        userService.update(user);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", true);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "检测支付密码是否为空")
    @RequestMapping(value = "/selectPayPassword",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object selectPayPassword(
            @RequestHeader(value = "X-Auth-Token", required = false) String token

    ) {
        ResourceBundle myResourcesBundle = International.getLanguage(request);
        Integer user_id = (Integer) request.getAttribute("USER_ID");

        User user = userService.get(user_id);
        boolean result = true;
        if (user.getPayPassword() == null || user.getPayPassword().isEmpty()) {
            result = false;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }


}
